/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2020-05-19 14:37
 */
package com.yao.common.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.yao.common.bean.LoginUser;
import com.yao.common.constant.RedisConst;
import com.yao.common.constant.SysConst;
import com.yao.common.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆拦截器
 *
 * @author yaoyuming
 * @date 2020/05/19 14:37
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 重定向
     */
    private final static String REDIRECT = "/home/login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

        String access_token = request.getHeader(SysConst.TOKEN_KEY);

        log.info("token :{}", access_token);

        if (!checkToken(access_token)) {
            log.info("access_token校验失败，跳转到登陆页面. url =  {}", request.getRequestURL());
            request.getRequestDispatcher(REDIRECT).forward(request, response);
            return false;
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
        log.info("校验access_token:[{}]通过.", request.getHeader(SysConst.TOKEN_KEY));
    }

    private boolean checkToken(String token) {

        if (StrUtil.isBlank(token)) {
            return false;
        }

        String res = RedisUtils.get(RedisConst.PRE_ACCESS_TOKEN + token);

        LoginUser loginUser;

        try {
            loginUser = JSON.parseObject(res, LoginUser.class);
        } catch (JSONException e) {
            log.error("解析失败.", e);
            return false;
        }

        log.info("登陆用户:{}", loginUser);

        return true;
    }

}